package com.css.fxfzdzzh.modules.mapManagement.service;

import com.css.fxfzdzzh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzdzzh.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzdzzh.base.dict.repository.DictItemRepository;
import com.css.fxfzdzzh.base.dict.repository.DictRepository;
import com.css.fxfzdzzh.base.dict.repository.entity.DictEntity;
import com.css.fxfzdzzh.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.common.utils.BeanUtil;
import com.css.fxfzdzzh.common.utils.ZipDownloadUtil;
import com.css.fxfzdzzh.constants.YNEnum;
import com.css.fxfzdzzh.modules.hypergraph.service.HypergraphService;
import com.css.fxfzdzzh.modules.mapManagement.entity.MapTemplate;
import com.css.fxfzdzzh.modules.mapManagement.param.MapTemplateQueryParam;
import com.css.fxfzdzzh.modules.mapManagement.repository.MapTemplateRepository;
import com.css.fxfzdzzh.modules.mapManagement.vo.MapTemplateVO;
import com.css.fxfzdzzh.modules.mapManagement.vo.MapTemplateViewVO;
import com.css.fxfzdzzh.util.CreateGson;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import com.css.fxfzdzzh.util.UUIDGenerator;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2023年05月17日  16:53
 */
@Service
public class MapTemplateService {

    @Resource
    MapTemplateRepository mapTemplateRepository;
    @Resource
    SUserService sUserService;
    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;
    @Value("${file.localDir}")
    private String localDir;
    @Resource
    private DictRepository dictRepository;
    @Resource
    private DictItemRepository dictItemRepository;
    @Resource
    private HypergraphService hypergraphService;

    public void uploadMapTemplate(MapTemplateVO vo) {
        MapTemplate map = new MapTemplate();
        //上传模板文件到超图模板目录
        String smTemplateName = null;
        RestResponse res = hypergraphService.uploadTemplateFile(vo.getAttachmentId());
        if(res.getCode()==200){
            smTemplateName = (String) res.getData();
        }
        if (PlatformObjectUtils.isEmpty(smTemplateName)){
            System.out.println("上传模板文件到超图模板目录失败");
        }
        map.setSmTemplateName(smTemplateName);//超图Web打印模板名称
        map.setDmtId(UUIDGenerator.getUUID());
        BeanUtils.copyProperties(vo,map);
        map.setUploadTime(new Date());
        String userId = PlatformSessionContext.getUserID();
        map.setUploadUserId(userId);
        String userJson = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        map.setUploadUserName(sUser.getUserName());
        map.setDelFlag(YNEnum.N.toString());
        mapTemplateRepository.saveMap(map);
    }

    public Map<String, Object> mapTemplatePage(MapTemplateQueryParam param, int curPage, int pageSize) {
        Map<String, Object> map =  mapTemplateRepository.mapTemplatePage(param, curPage, pageSize);
        List<MapTemplate> list = (List<MapTemplate>) map.get("rows");
        if(PlatformObjectUtils.isNotEmpty(list) && list.size()>0){
            List<DictEntity> all = dictRepository.findAll();
            java.util.Map<String, String> dictMap = all.stream().collect(Collectors.toMap(DictEntity::getDictId, DictEntity::getDictName));
            list.forEach(entity->{
                DictItemEntity dictItemEntity = dictItemRepository.findOneByDictItemIdAndDictId(entity.getMapLevel1Category(),entity.getMapLevel2Category());
                entity.setMapLevel2Category(dictItemEntity.getDictItemName());
                entity.setMapLevel1Category(dictMap.get(entity.getMapLevel1Category()));
            });
        }
        return map;
    }

    public void delete(List<String> dmtIdList) {
        int count = mapTemplateRepository.delete(dmtIdList);
        if(count==0){
            throw new RuntimeException("删除失败");
        }
    }

    public void download(List<String> attacheIdList, HttpServletResponse resp) {
        List<File> fileList = new ArrayList<>();
        attacheIdList.forEach(attacheId->{
            AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(attacheId);
            File file = new File(attach.getFileDirId()+File.separator+attach.getAttachPath());
            fileList.add(file);
        });
        if(fileList.size()>0){
            ZipDownloadUtil.zipDownload(resp,localDir,"图件"+System.currentTimeMillis()+".zip",fileList);
        }
    }

    public MapTemplateViewVO getById(String dmtId) {
       MapTemplate mapTemplate = mapTemplateRepository.getById(dmtId);
       if(mapTemplate==null){
           return new MapTemplateViewVO();
       }
        MapTemplateViewVO vo = new MapTemplateViewVO();
        AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(mapTemplate.getAttachmentId());
        BeanUtil.copyPropertiesIgnoreEmpty(mapTemplate,vo);
        vo.setAttachList(Arrays.asList(attach));
        return vo;
    }

    //用附件ID查找图件模板信息
    public MapTemplate getByAttachId(String attachId) {
        MapTemplate mapTemplate = mapTemplateRepository.getByAttachId(attachId);
        return mapTemplate;
    }
}
